package org.jadedanha.dao;

import java.sql.*;
import java.util.*;
import org.jadedanha.model.*;

public class UsuarioDao extends Dao {

    public void save(Usuario usuario) throws SQLException {
        String sql;

        if ( usuario.getId() == null ) {
            sql = "INSERT INTO usuario(nome, email, senha) VALUES(?, ?, ?) ";
        } else {
            sql = "UPDATE usuario SET nome = ?, email = ?, senha = ? WHERE id = ?";
        }

        PreparedStatement stm = this.getConnection().prepareStatement(sql);

        stm.setString(1, usuario.getNome() );
        stm.setString(2, usuario.getEmail().toString() );
        stm.setString(3, usuario.getSenha().toString() );

        if ( usuario.getId() != null ) {
            stm.setInt(1, usuario.getId() );
        }
    
        stm.execute();
        stm.close();
    }

    public void delete(Usuario usuario) throws SQLException {
        String            sql = "DELETE FROM usuario WHERE id = ?";
        PreparedStatement stm = this.getConnection().prepareStatement(sql);

        stm.setInt(1, usuario.getId() );

        stm.execute();
        stm.close();
    }

    public List<Usuario> list() throws SQLException {
        List<Usuario>    list = new ArrayList<Usuario>();
        String            sql = "SELECT * FROM usuario ORDER BY nome,email";
        PreparedStatement stm = this.getConnection().prepareStatement(sql);
        ResultSet         rs  = stm.executeQuery();

        while (rs.next() ) {
            Usuario u = new Usuario()
                .setId( rs.getInt("id") )
                .setNome( rs.getString("nome") )
                .setEmail( new Email( rs.getString("email") ) )
                .setSenha( new Senha( rs.getString("senha") ) );

            list.add( u );
        }

        return list;
    }

    public static void main(String[] dsaf) {
        UsuarioDao dao = new UsuarioDao();
        Usuario u      = new Usuario()
            .setNome("Joao2")
            .setEmail( new Email("alexander@email.com") )
            .setSenha( new Senha("123")            );

        try {
            dao.save(u);
            System.out.println("Salvou .... aeeeeeee");
        } catch( Exception e ) {
            System.out.println("Deu merda!!!");
            e.printStackTrace();
        }

        try {
            for (Usuario us : dao.list() ) {
                System.out.println( us );
            }
        } catch( Exception e ) {
            System.out.println("Deu merda!!!");
            e.printStackTrace();
        }
    }
}

